package com.youdianstar.app.support.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.youdianstar.app.api.ApiService
import com.youdianstar.app.entity.BranchInfo
import com.youdianstar.app.common.PAGE_SIZE
import com.youdianstar.app.common.event.NetEventLiveData
import java.io.IOException


/**
 * File: BranchPagingSource
 * Author: 82149 Create: 2021/9/29 15:27
 * Changes (from 2021/9/29)
 * --------------------------------------------------
 * description: Paging3 使用样例,只适合按页数分页不合适按下标加载
 *              可以做数据的复杂加载: 比如缓存,数据库,网路接口
 * ---------------------------------------------------
 *
 */
class BranchPagingSource( private val service: ApiService,
    var lng: Double,
    var lat: Double,
    var searchKey: String,
    var dataType: Int?,
    private val eventLiveData: NetEventLiveData? = null
) : PagingSource<Int, BranchInfo>() {

    override fun getRefreshKey(state: PagingState<Int, BranchInfo>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, BranchInfo> {
        val index = params.key ?: 0
        try {
            // 使用新接口 V2
            val response = service.getBranchListV2(
                lng = lng, 
                lat = lat, 
                search = searchKey.ifEmpty { null }, 
                type = dataType,
                distance = 5,
                total = 200
            )
            
            android.util.Log.d("BranchPagingSource", "接口返回: code=${response.code}, message=${response.message}")
            android.util.Log.d("BranchPagingSource", "响应类型: ${response.javaClass}")
            android.util.Log.d("BranchPagingSource", "data字段: ${response.data?.javaClass}")
            android.util.Log.d("BranchPagingSource", "数据大小: ${response.data?.size ?: 0}")
            
            // API返回SiteInfo数组，转换为BranchInfo
            val dataList = response.data?.map { it.toBranchInfo() } ?: emptyList()
            
            // 根据type过滤数据
            val filteredList = when (dataType) {
                1 -> dataList.filter { it.rent > 0 && it.isBusiness } // 可租借
                2 -> dataList.filter { it.recovery > 0 && it.isBusiness } // 可归还
                else -> dataList // 全部
            }
            
            android.util.Log.d("BranchPagingSource", "过滤后数据大小: ${filteredList.size}")
            
            // 分页处理
            val result = filteredList.drop(index).take(PAGE_SIZE)
            
            android.util.Log.d("BranchPagingSource", "分页数据: index=$index, size=${result.size}")
            
            if (index == 0 && result.isEmpty()) {
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_EMPTY)
            } else {
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_OK)
            }
            
            return LoadResult.Page(
                result,
                prevKey = null,
                nextKey = if (result.size < PAGE_SIZE || index + PAGE_SIZE >= filteredList.size) null else index + PAGE_SIZE
            )
        } catch (e: IOException) {
            android.util.Log.e("BranchPagingSource", "IOException", e)
            if (index == 0)
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_ERROR)
            return LoadResult.Error(e)
        } catch (e: Exception) {
            android.util.Log.e("BranchPagingSource", "Exception", e)
            eventLiveData?.postValue(NetEventLiveData.Result.NET_ERROR)
            return LoadResult.Error(e)
        }
    }
}